from django.shortcuts import render, redirect, reverse
from django.core.paginator import Paginator
from django.db.models import Q
from teacher.models import Student, StudentDetail, Grade, Course, Enroll
from teacher.forms import StudentForm, StudentDetailForm
# Create your views here.

def index(request):

    section = '学生列表'

    search = request.POST.get('search', '').strip()
    if search:
        if search.isdigit():
            stus = Student.objects.filter(Q(qq=search)|Q(mobile=search), is_delete=False)
        else:
            stus = Student.objects.filter(Q(name=search)|Q(webchat=search), is_delete=False)
    else:
        stus = Student.objects.filter(is_delete=False)
        stus = stus.order_by('-c_time')  # 按入学时间反向排序

    total_num = stus.count() # 总数量
    num_perpage = request.GET.get('num_perpage', 3) # 每页显示的数量
    current_page = request.GET.get('current_page', 1) # 当前页码

    p = Paginator(stus, num_perpage, allow_empty_first_page=True)
    stus = p.get_page(current_page) # 每页显示的数据
    total_pages = p.num_pages # 总页数

    return render(request, 'teacher/index.html', context={
        'stus': stus,
        'section': section,
        'search': search,
        'total_pages': total_pages,
        'total_num': total_num,
        'current_page': current_page,
        'num_perpage': num_perpage,
        'p': p,
    })

def student_delete(request, pk):

    stu = Student.objects.get(pk=pk)
    stu.is_delete = True
    stu.save()
    return redirect(index)

def student_detail(request, pk):

    grades = Grade.objects.all()
    stu = Student.objects.get(pk=pk)

    return render(request, 'teacher/student_detail.html', context={
        'section': '学生详情',
        'grades': grades,
        'stu': stu,
    })

def sutdent_add(request):

    section = '添加学生'
    grades = Grade.objects.all()
    if request.method == 'GET':
        return render(request, 'teacher/student_detail.html', context={
            'section': section,
            'grades': grades,
        })
    elif request.method == 'POST':
        stu = {
            'name': request.POST.get('name'),
            'age': request.POST.get('age'),
            'sex': request.POST.get('sex'),
            'qq': request.POST.get('qq'),
            'mobile': request.POST.get('mobile'),
            'webchat': request.POST.get('webchat'),
        }

        student = Student.objects.create(**stu)
        StudentDetail.objects.create(
            num=request.POST.get('num'),
            collage=request.POST.get('collage'),
            student=student,
        )
        return redirect(reverse('teacher:index'))

def student_modify(request, pk):

    section = '编辑学生'
    stu = Student.objects.get(pk=pk)
    grades = Grade.objects.all()
    try:
        detail = StudentDetail.objects.get(student_id=pk) # 如果查询不到记录则会抛异常，使用try来处理！
    except:
        detail = StudentDetail()

    if request.method == 'GET':
        return render(request, 'teacher/student_detail.html', context={
            'section': section,
            'stu': stu,
            'grades': grades,
            'detail': detail,
        })
    elif request.method == 'POST':
        grade_id = request.POST.get('grade')
        grade = Grade.objects.get(pk=grade_id) if grade_id else None
        stu.name = request.POST.get('name')
        stu.age = request.POST.get('age')
        stu.sex = request.POST.get('sex')
        stu.qq = request.POST.get('qq')
        stu.mobile = request.POST.get('mobile')
        stu.webchat = request.POST.get('webchat')
        stu.grade = grade
        stu.save()

        detail.num = request.POST.get('num')
        detail.collage = request.POST.get('collage')
        detail.student = stu
        detail.save()

        return redirect(reverse('teacher:index'))

def student_modify_modelform(request, pk):

    section = '编辑学生'
    stu = Student.objects.get(pk=pk)
    grades = Grade.objects.all()
    try:
        detail = StudentDetail.objects.get(student_id=pk) # 如果查询不到记录则会抛异常，使用try来处理！
    except:
        detail = StudentDetail()

    if request.method == 'GET':
        form = StudentForm(instance=stu)
        detail_form = StudentDetailForm(instance=detail)
        # try:
        #     detail_form = StudentDetailForm(instance=stu.studentdetail)
        # except:
        #     student_detail = StudentDetail()
        #     student_detail.student = stu
        #     student_detail.save()
        #     detail_form = StudentDetailForm(instance=student_detail)

    elif request.method == 'POST':
        form = StudentForm(request.POST, instance=stu)
        detail_form = StudentDetailForm(request.POST, instance=detail)
        if form.is_valid() and detail_form.is_valid():
            form.save()
            detail_form.save()
            return redirect(reverse('teacher:index'))
    return render(request, 'teacher/student_detail_modelform.html', context={
        'section': section,
        'stu': stu,
        'form': form,
        'detail_form': detail_form,
        'grades': grades,
        'detail': detail,
    })